#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "ohos_init.h"
#include "ohos_types.h"
#include "cmsis_os2.h"
#include "iot_errno.h"
#include "iot_uart.h"

#define IOT_UART 1
uint8_t buffer[1024] = {0};

static void UARTTask(void)
{
    IotUartAttribute uart_attr =
    {
        .baudRate = 9600,                       // 波特率
        .dataBits = IOT_UART_DATA_BIT_8,        // 数据位
        .stopBits = IOT_UART_STOP_BIT_1,        // 停止位
        .parity   = IOT_UART_PARITY_NONE,       // 奇偶校验
        .rxBlock  = IOT_UART_BLOCK_STATE_BLOCK, // 接收是否阻塞
        .txBlock  = IOT_UART_BLOCK_STATE_BLOCK, // 发送是否阻塞
        .pad      = 0,
    };
    // 初始化 UART1
    uint32_t ret = IoTUartInit(IOT_UART, &uart_attr);
    if (ret != IOT_SUCCESS)
    {
        printf("Failed to init UART! Error: %d\n", ret);
        return;
    }
    while (1)
    {
        // 通过串口 1 接收数据
        IoTUartRead(IOT_UART, buffer, sizeof(buffer));
        // 通过串口 1 发送收到的数据
        IoTUartWrite(IOT_UART, buffer, strlen((char*) buffer));
    }
}

void UARTExample(void)
{
    osThreadAttr_t attr;
    attr.name = "UARTTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 512;
    attr.priority = osPriorityNormal;
    if (osThreadNew((osThreadFunc_t) UARTTask, NULL, &attr) == NULL)
    {
        printf("Failed to create UARTTask!\n");
    }
}

SYS_RUN(UARTExample);
